package controller

import (
	"strconv"

	"system-admin/config/mysql"
	"system-admin/internal/models"
	"system-admin/pkg"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
)

type Area struct{}

// ALL 所有的区域信息
func (Area) AllTree(c *gin.Context) {
	maxLevel, _ := strconv.Atoi(c.Query("max_level"))
	if maxLevel <= 0 || maxLevel >= 4 {
		maxLevel = 3
	}
	tree, err := pkg.NewAreaTree().Get(maxLevel)
	if err != nil {
		response.JSON(c, []string{}, err)
		return
	}
	response.JSON(c, tree, nil)
}

// ALL 所有的区域信息
func (Area) All(c *gin.Context) {
	maxLevel, _ := strconv.Atoi(c.Query("max_level"))
	if maxLevel <= 0 || maxLevel >= 4 {
		maxLevel = 3
	}
	// 获取记录
	var areas []models.Area
	rowsAffected := mysql.NewDB().Model(&models.Area{}).Where("level <= ?", maxLevel).Find(&areas).RowsAffected
	response.JSON(c, map[string]interface{}{
		"list":  areas,
		"total": rowsAffected,
	}, nil)
}

// 获取某个区域的下级区域列表
func (Area) List(c *gin.Context) {
	PID := c.Query("pid")
	if PID == "" {
		response.JSON(c, nil, errorx.New("父级id不能为空"))
		return
	}
	// 获取记录
	var areas []models.Area
	rowsAffected := mysql.NewDB().Model(&models.Area{}).Where("parent_id = ?", PID).Find(&areas).RowsAffected
	response.JSON(c, map[string]interface{}{
		"list":  areas,
		"total": rowsAffected,
	}, nil)
}
